<template>
  <view>
    <view class="goods-list">
      <view class="goods-tabs">
        <lyz-tabs :list="sortList" @sort="sortChoose"></lyz-tabs>
      </view>
      <view v-for="(goods, i) in sortedGoodList" :key="i" @click="gotoDetail(goods)">
        <lyz-goods :goods="goods"></lyz-goods>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        // 请求参数对象
        queryObj: {
          query: '',
          cid: '',
          pagenum: 1,
          pagesize: 10
        },
        goodsList: [],
        total: 0,
        // 节流阀
        isloading: false,
        sortList: ["综合", "价格▲", "价格下▼"], //排序选项
        sortIndex: 0, //当前选中的排序下标


      };
    },
    onLoad(options) {
      this.queryObj.query = options.query || ''
      this.queryObj.cid = options.cid || ''
      this.getGoodsList()
    },
    computed: {
      //选择排序的方法
      sortedGoodList() {
        if (this.sortIndex == 1) {
          return [...this.goodsList].sort((a, b) => a.goods_price - b.goods_price);

        } else if (this.sortIndex == 2) {
          return [...this.goodsList].sort((a, b) => b.goods_price - a.goods_price);
        } else {
          return this.goodsList;
        }

      }
    },
    methods: {
      sortChoose(index) {
        this.sortIndex = index;

      },
      // 获取商品列表数据的方法
      async getGoodsList(cb) {
        // 打开节流阀
        this.isloading = true
        const {
          data: res
        } = await uni.$http.get('/api/public/v1/goods/search', this.queryObj)
        // 关闭节流阀
        this.isloading = false
        cb && cb()
        if (res.meta.status !== 200) return uni.$showMsg()

        this.goodsList = [...this.goodsList, ...res.message.goods]
        this.total = res.message.total
      },
      gotoDetail(goods) {
        uni.navigateTo({
          url: '/subpkg/goods_detail/goods_detail?goods_id=' + goods.goods_id
        })
      }
    },
    onReachBottom() {
      if (this.queryObj.pagenum * this.queryObj.pagesize >= this.total) return uni.$showMsg('数据加载完毕!')

      if (this.isloading) return

      // 让页码值自增+1
      this.queryObj.pagenum++
      this.getGoodsList()
    },
    onPullDownRefresh() {
      // 重置关键数据
      this.queryObj.pagenum = 1
      this.total = 0
      this.isloading = false
      this.goodsList = []

      // 重新发起数据请求
      this.getGoodsList(() => uni.stopPullDownRefresh())
    }
  }
</script>

<style lang="scss">
  .goods-list {
    height: 100%;

    .goods-tabs {
      position: sticky;
      top: 0;
      left: 0;
      width: 100%;
    }
  }
</style>